package net.example.lesson5;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ${user}
 * @version V1.0
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}(用一句话描述该文件做什么)
 * @date ${date}
 */
public class ReentrantLockTest {
    private static ReentrantLock lock = new ReentrantLock();

    /**
     * 限时等待.
     */
    public static void action() {
        try {
            if (lock.tryLock(5, TimeUnit.SECONDS)) {
                System.out.println(Thread.currentThread().getName() + " 执行Action1");
                TimeUnit.SECONDS.sleep(10);
            } else {
                System.out.println(Thread.currentThread().getName() + " 获取锁失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new LockTask());
        Thread thread2 = new Thread(new LockTask());
        thread1.start();
        thread2.start();
    }

    static class LockTask implements Runnable {
        @Override
        public void run() {
            action();
        }
    }
}